//
//  setLockPwdViewController.m
//  QRMaster
//
//  Created by myApple on 15/12/1.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "setLockPwdViewController.h"
#import "LineView.h"
#import "RequestNetWork.h"
#import "MyRsa.h"
#import "PromptInfoView.h"
#import "Reachability.h"
#import "GetSecretViewController.h"
#import "openssl/rsa.h"
#import "CRSA.h"

@interface setLockPwdViewController ()<UITextFieldDelegate>
{
    UILabel * titleLabel;
    UITextField * oldTextField;
    UITextField * newTextField;
    NSUserDefaults * userInfo;
    
    UIImageView * oldPWDView;
    UIImageView * NewPDView;
    UIImageView * AngainPWDView;
    UIButton * forgetBnt;
    
    UILabel * oldPwdLabel;
    UILabel * newPwdLabel;
    UIButton * makeSureBtn;
    UIButton * oldSeeBtn;
    UIButton * newSeeBtn;
    UIView * passWordView;
    UIButton * withoutOldPwdBtn;
    UISwitch * withoutOldSwitch;
    CRSA * crsa;
}

@end

@implementation setLockPwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
    self.title = NSLocalizedString(@"modifyKey", nil);
    userInfo = [NSUserDefaults standardUserDefaults];
    [self prepareView];
    crsa = [CRSA shareInstance];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    titleLabel.text = NSLocalizedString(@"modifyPWD", nil);
    //    oldPwdLabel.text = NSLocalizedString(@"oldLoginPWD", nil);
    //    oldTextField.placeholder = NSLocalizedString(@"inputLoginPWD", nil);
    //    newPwdLabel.text = NSLocalizedString(@"newPassWord", nil);
    //    newTextField.placeholder = NSLocalizedString(@"loginingPromt", nil);
    //    againPwdLabel.text = NSLocalizedString(@"makeSurePWD", nil);
    //    againTextField.placeholder = NSLocalizedString(@"inputAgainLogin", nil);
    //    [makeSureBtn setTitle:NSLocalizedString(@"alterSure", nil) forState:0];
}

-(void)prepareView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    //    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 16;
    float width = ScreenWidth;
    float height = 44;
    
    passWordView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    passWordView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:passWordView];
    
    x = 16;
    y = 14;
    height = 16;
    width = 100;
    oldPwdLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    oldPwdLabel.text = NSLocalizedString(@"originKey", nil);
    oldPwdLabel.textColor = UIColorFromRGB(0x333333);
    oldPwdLabel.font = [UIFont systemFontOfSize:13.0];
    oldPwdLabel.textColor = UIColorFromRGB(0x333333);
    [passWordView addSubview:oldPwdLabel];
    
    x = 130;
    width = ScreenWidth - x;
    oldTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, 0, width, 44)];
//    oldTextField.placeholder = NSLocalizedString(@"inputOldKey", nil);
    oldTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"inputOldKey", nil) attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x727272)}];
    oldTextField.font = [UIFont systemFontOfSize:13.0];
    oldTextField.textColor = UIColorFromRGB(0x333333);
    oldTextField.delegate = self;
    oldTextField.secureTextEntry = YES;
    oldTextField.keyboardType = UIKeyboardTypeNumberPad;
    [passWordView addSubview:oldTextField];
    //小眼睛
    UIImageView * oldSeeImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    oldTextField.rightViewMode = UITextFieldViewModeAlways;
    oldTextField.rightView = oldSeeImgView;
    oldSeeImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * oldSeeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seeOldTap)];
    [oldSeeImgView addGestureRecognizer:oldSeeTap];
    oldSeeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    oldSeeBtn.frame = CGRectMake(8, 16, 16, 12);
    oldSeeBtn.selected = NO;
    oldSeeBtn.userInteractionEnabled = NO;
    [oldSeeBtn setBackgroundImage:[UIImage imageNamed:@"Browse"] forState:UIControlStateNormal];
    [oldSeeBtn setBackgroundImage:[UIImage imageNamed:@"GreenBrowse"] forState:UIControlStateSelected];
    [oldSeeImgView addSubview:oldSeeBtn];
    
    //新密钥
    x = 0;
    y = passWordView.frame.size.height + passWordView.frame.origin.y + 0.5;
    height = 44;
    width = ScreenWidth;
    UIView * newPassWordView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    newPassWordView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:newPassWordView];
    
    x = 16;
    y = 14;
    height = 16;
    width = 100;
    newPwdLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    newPwdLabel.text = NSLocalizedString(@"newKey", nil);
    newPwdLabel.textColor = UIColorFromRGB(0x333333);
    newPwdLabel.font = [UIFont systemFontOfSize:13.0];
    [newPassWordView addSubview:newPwdLabel];
    
    x = 130;
    width = ScreenWidth - x;
    newTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, 0, width, 44)];
//    newTextField.placeholder = NSLocalizedString(@"inputNewKey", nil);
    newTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"inputNewKey", nil) attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x727272)}];
    newTextField.textColor = UIColorFromRGB(0x333333);
    newTextField.font = [UIFont systemFontOfSize:13.0];
    newTextField.secureTextEntry = YES;
    newTextField.delegate = self;
    newTextField.keyboardType = UIKeyboardTypeNumberPad;
    [newPassWordView addSubview:newTextField];
    
    //小眼睛
    UIImageView * newSeeImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    newTextField.rightViewMode = UITextFieldViewModeAlways;
    newTextField.rightView = newSeeImgView;
    newSeeImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * newSeeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seeNewTap)];
    [newSeeImgView addGestureRecognizer:newSeeTap];
    newSeeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    newSeeBtn.frame = CGRectMake(8, 16, 16, 12);
    newSeeBtn.selected = NO;
    newSeeBtn.userInteractionEnabled = NO;
    [newSeeBtn setBackgroundImage:[UIImage imageNamed:@"Browse"] forState:UIControlStateNormal];
    [newSeeBtn setBackgroundImage:[UIImage imageNamed:@"GreenBrowse"] forState:UIControlStateSelected];
    [newSeeImgView addSubview:newSeeBtn];
    
    //恢复原密钥
    y = newPassWordView.frame.size.height + newPassWordView.frame.origin.y + 28;
    height = 14;
    x = 16;
    width = 100;
    forgetBnt = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetBnt.frame = CGRectMake(x, y, width, height);
    [forgetBnt setTitle:NSLocalizedString(@"forgetKey", nil) forState:UIControlStateNormal];
    forgetBnt.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [forgetBnt setTitleColor:UIColorFromRGB(0x7dc234) forState:UIControlStateNormal];
    [forgetBnt addTarget:self action:@selector(forgetClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetBnt];
    
    //自适应长度
    width = [self calculateWidth:NSLocalizedString(@"forgetKey", nil)];
    forgetBnt.frame = CGRectMake(x, y, width, height);
    
    x = ScreenWidth - 177;
    y = forgetBnt.frame.origin.y;
    width = 100;
    height = 20;
    withoutOldPwdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    withoutOldPwdBtn.frame = CGRectMake(x, y, width, height);
    [withoutOldPwdBtn setTitle:NSLocalizedString(@"factorySet", nil) forState:0];
    [withoutOldPwdBtn setTitleColor:UIColorFromRGB(0x727272) forState:UIControlStateNormal];
    withoutOldPwdBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [self.view addSubview:withoutOldPwdBtn];
    withoutOldPwdBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    withoutOldPwdBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    
    withoutOldSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(ScreenWidth - 51 - 16, y - 5, 51, 31)];
    withoutOldSwitch.backgroundColor = [UIColor clearColor];
    [withoutOldSwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
    withoutOldSwitch.onTintColor = RGBA(135, 199, 66, 1);
    [self.view addSubview:withoutOldSwitch];
    
    
    x = 16;
    width = ScreenWidth - 2 * x;
    height = 48;
    y = withoutOldSwitch.frame.size.height + withoutOldSwitch.frame.origin.y + 38;
    makeSureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    makeSureBtn.frame = CGRectMake(x, y, width, height);
    makeSureBtn.layer.cornerRadius = 5.0;
    makeSureBtn.layer.masksToBounds = YES;
    [makeSureBtn setTintColor:[UIColor whiteColor]];
    [makeSureBtn setTitle:NSLocalizedString(@"alterSure", nil) forState:0];
    makeSureBtn.titleLabel.font = [UIFont systemFontOfSize:19];
    [makeSureBtn setBackgroundColor:UIColorFromRGB(0x7dc234)];
    [makeSureBtn addTarget:self action:@selector(makesureClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:makeSureBtn];
    
    UITapGestureRecognizer * removeKeyBoardTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyboard)];
    [self.view addGestureRecognizer:removeKeyBoardTap];
}

-(void)getData
{
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [rnk initWithPath:POST(GETMODIFYVCODE) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil) {
        }
        else if ([[error objectForKey:@"status"]integerValue] == 167) {
            
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
        }

    }];
   
}

-(void)makesureClick
{
    [oldTextField resignFirstResponder];
    [newTextField resignFirstResponder];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    if (withoutOldSwitch.on) {
        [postDict setValue:@"" forKey:@"oldPassword"];
        [postDict setValue:@"1" forKey:@"isFirst"];
    }
    else
    {
        if (oldTextField.text.length == 0) {
            [PromptInfoView showMessage:NSLocalizedString(@"originKeyEmpty", nil)];
            return;
        }
        if (![self isPureInt:oldTextField.text] || oldTextField.text.length != 16) {
            [PromptInfoView showMessage:NSLocalizedString(@"originKeyWrong", nil)];
            return;
        }
        NSString * oldpassword = [crsa encryptByRsa:oldTextField.text withKeyType:KeyTypePublic];
        [postDict setValue:oldpassword forKey:@"oldPassword"];
        [postDict setValue:@"0" forKey:@"isFirst"];
    }
    
    if (newTextField.text.length == 0) {
        [PromptInfoView showMessage:NSLocalizedString(@"newKeyEmpty", nil)];
        return;
    }
    
    if (![self isPureInt:newTextField.text] || newTextField.text.length != 16) {
        [PromptInfoView showMessage:NSLocalizedString(@"newKeyWrong", nil)];
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSString * newpassword = [crsa encryptByRsa:newTextField.text withKeyType:KeyTypePublic];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:newpassword forKey:@"newPassword"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [rnk initWithPath:POST(MODIFYLOCKPASSWORD) params:postDict block:^(id downLoadData, id error) {
        makeSureBtn.enabled = YES;
        [self stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil) {
            [PromptInfoView showMessage:NSLocalizedString(@"modifySuccess", nil)];
            [self BackClick];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
            
        }

    }];
}


-(NSString *)getPassword:(NSString *)password
{
    MyRsa * rsa = [[MyRsa alloc]init];
    if (rsa != nil) {
        NSString * encryptPWD = [rsa RSAEncrypotoTheData:[NSString stringWithFormat:@"12345678%@",password] key:publicKeyString];
        encryptPWD = [encryptPWD stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        return encryptPWD;
    }
    else
        return nil;
    
}


-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == oldTextField) {
        oldPWDView.image = [UIImage imageNamed:@"36密码可见"];
    }
    else if (textField == newTextField)
    {
        NewPDView.image = [UIImage imageNamed:@"36密码可见"];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == oldTextField) {
        oldPWDView.image = [UIImage imageNamed:@"36密码不可见"];
    }
    else if (textField == newTextField)
    {
        NewPDView.image = [UIImage imageNamed:@"36密码不可见"];
    }
}

-(void)seeOldTap
{
    oldSeeBtn.selected = !oldSeeBtn.selected;
    if (oldSeeBtn.selected) {
        oldTextField.secureTextEntry = NO;
    }
    else
    {
        oldTextField.secureTextEntry = YES;
    }
}

-(void)seeNewTap
{
    newSeeBtn.selected = !newSeeBtn.selected;
    if (newSeeBtn.selected) {
        newTextField.secureTextEntry = NO;
    }
    else
    {
        newTextField.secureTextEntry = YES;
    }
}

-(void)changeSwitch:(UISwitch *)ch
{
    if (ch.on) {
//        passWordView.backgroundColor = RGBA(225, 225, 225, 1);
        passWordView.backgroundColor = UIColorFromRGBAndA(0xc1c1c1, 0.5);
        oldTextField.userInteractionEnabled = NO;
        oldTextField.text = @"";
        oldSeeBtn.selected = NO;
//        oldPwdLabel.textColor = RGBA(160, 160, 160, 1);
        [withoutOldPwdBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:UIControlStateNormal];
        forgetBnt.enabled = NO;
        [forgetBnt setTitleColor:UIColorFromRGB(0x727272) forState:UIControlStateNormal];
    }
    else
    {
        passWordView.backgroundColor = [UIColor whiteColor];
        oldTextField.userInteractionEnabled = YES;
//        oldPwdLabel.textColor = [UIColor blackColor];
        oldPwdLabel.textColor = UIColorFromRGB(0x333333);
        [withoutOldPwdBtn setTitleColor:UIColorFromRGB(0x727272) forState:UIControlStateNormal];
        forgetBnt.enabled = YES;
        [forgetBnt setTitleColor:UIColorFromRGB(0x7dc234) forState:UIControlStateNormal];
    }
}

#pragma mark -- roomNo自适应长度
-(CGFloat)calculateWidth:(NSString *)str
{
    CGSize size =CGSizeMake(self.view.frame.size.width,20);
    
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12.0],NSFontAttributeName,nil];
    
    //ios7方法，获取文本需要的size，限制宽度
    
    CGSize  actualsize =[str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    return actualsize.width;
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self hiddenKeyboard];
    return YES;
}


//密钥验证
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

-(void)forgetClick
{
    GetSecretViewController * fpc = [[GetSecretViewController alloc]init];
    fpc.communityId = _communityId;
    withoutOldSwitch.on = NO;
    [self changeSwitch:withoutOldSwitch];
    oldSeeBtn.selected = NO;
    fpc.oldPassWord = ^(NSString * oldPwd)
    {
        oldTextField.text = oldPwd;
        oldTextField.secureTextEntry = NO;
    };
    [self.navigationController pushViewController:fpc animated:YES];
}

-(void)hiddenKeyboard
{
    [oldTextField resignFirstResponder];
    [newTextField resignFirstResponder];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)BackClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
